package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.CityAdapter;
import com.luck.easyfoodbatch.db.FindDB;
import com.luck.easyfoodbatch.entity.City;
import com.luck.easyfoodbatch.entity.CityEntity;
import com.luck.easyfoodbatch.indexablelistview.IndexEntity;
import com.luck.easyfoodbatch.indexablelistview.IndexHeaderEntity;
import com.luck.easyfoodbatch.indexablelistview.IndexableStickyListView;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LocationActivity extends BaseActivity {

    @BindView(R.id.left_back)
    ImageButton leftBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.input_search_query)
    EditText inputSearchQuery;
    @BindView(R.id.searchBarContainer)
    RelativeLayout searchBarContainer;
    @BindView(R.id.indexListView)
    IndexableStickyListView indexListView;
    @BindView(R.id.ll_del)
    LinearLayout llDel;
    private CityEntity gpsEntity;
    private IndexHeaderEntity<CityEntity> gpsHeader;
    private CityAdapter mAdapter;
    private List<CityEntity> mCities = new ArrayList<>();
    private FindDB findDB;
    public LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    public BDLocation lastLocation = null;
    private String p_id = "";
    private String p_name = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location, "选择地区", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        p_id = (String) SharedPreferencesUtil.getData(LocationActivity.this, HttpUtil.P_ID, "");
        p_name = (String) SharedPreferencesUtil.getData(LocationActivity.this, HttpUtil.P_NAME, "");
        findDB = new FindDB(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                    getString(R.string.mis_permission_location),
                    ACCESS_COARSE_LOCATION_CODE);
        }
        initView();
        inputSearchQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    llDel.setVisibility(View.VISIBLE);
                } else {
                    llDel.setVisibility(View.GONE);
                }
            }
        });
    }

    private final int ACCESS_COARSE_LOCATION_CODE = 1002;

    @OnClick({R.id.ll_del})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_del:
                inputSearchQuery.setText("");
                break;
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            // 添加定位城市Header
            new AlertDialog.Builder(this)
                    .setTitle("定位权限")
                    .setMessage(rationale)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(LocationActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == ACCESS_COARSE_LOCATION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                gpsEntity.setName("定位中，请稍候...");
                mAdapter.notifyDataSetChanged();
                showMapWithLocationClient();
            } else {
                gpsEntity.setId("-1");
                gpsEntity.setName("定位失败...");
                mAdapter.notifyDataSetChanged();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void backClick() {
        if (!Tools.isNull(p_id)) {
            Intent intent = new Intent();
            intent.putExtra("name", p_name);
            intent.putExtra("id", p_id);
            setResult(RESULT_OK, intent);
            finish();
        } else {
            T.showToast(mContext, "请先选择定位地区~");
        }
    }

    protected void initView() {
        mAdapter = new CityAdapter(this, resetLocation);
        indexListView.setAdapter(mAdapter);

        // 初始化数据
        //List<String> cityStrings = Arrays.asList(getResources().getStringArray(R.array.city_array));
        List<City> provinces = findDB.getProvinces();
        for (City item : provinces) {
            CityEntity cityEntity = new CityEntity();
            cityEntity.setName(item.getName());
            cityEntity.setId(item.getId());
            mCities.add(cityEntity);
        }

        // 添加定位城市Header
        ArrayList<CityEntity> gpsIndexEntityList = new ArrayList<>();
        gpsEntity = new CityEntity();
        gpsEntity.setName("定位中，请稍候...");
        mAdapter.notifyDataSetChanged();
        gpsIndexEntityList.add(gpsEntity);
        gpsHeader = new IndexHeaderEntity<>("定", "GPS自动定位", gpsIndexEntityList);
        // 绑定数据
        indexListView.bindDatas(mCities, gpsHeader);
        showMapWithLocationClient();
        // 搜索
        inputSearchQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                indexListView.searchTextChange(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        indexListView.setOnItemContentClickListener(new IndexableStickyListView.OnItemContentClickListener() {
            @Override
            public void onItemClick(View v, IndexEntity indexEntity) {
                String indexEntityName = indexEntity.getName();
                if (Tools.isNull(indexEntityName) || indexEntityName.equals("定位中，请稍候...") || indexEntityName.equals("定位失败...")) {
                    T.showToast(mContext, "位置获取失败，请检查是否开启定位~");
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("name", indexEntityName);
                    intent.putExtra("id", indexEntity.getId());
                    String name = "";
                    if (!Tools.isNull(indexEntity.getName())) {
                        if (indexEntity.getName().endsWith("市")) {
                            name = indexEntity.getName().substring(0, indexEntity.getName().length() - 1);
                        } else {
                            name = indexEntity.getName();
                        }
                    }
                    SharedPreferencesUtil.saveData(LocationActivity.this, HttpUtil.P_ID, indexEntity.getId());
                    SharedPreferencesUtil.saveData(LocationActivity.this, HttpUtil.P_NAME, name);
                    sendBroadcast("app.action.refresh.location");
                    finish();
                }
            }
        });
    }

    /**
     * 重新定位
     */
    public CityAdapter.onResetLocation resetLocation = new CityAdapter.onResetLocation() {
        @Override
        public void onResetLocationBack() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                    && ActivityCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        getString(R.string.mis_permission_location),
                        ACCESS_COARSE_LOCATION_CODE);
            } else {
                gpsEntity.setName("定位中，请稍候...");
                showMapWithLocationClient();
                mAdapter.notifyDataSetChanged();
            }
        }
    };


    /**
     * 定位
     */
    private void showMapWithLocationClient() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// open gps
        // option.setCoorType("bd09ll");
        // Johnson change to use gcj02 coordination. chinese national standard
        // so need to conver to bd09 everytime when draw on baidu map
        option.setCoorType("gcj02");
        option.setScanSpan(30000);
        option.setAddrType("all");
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * format new location to string and show on screen
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            lastLocation = location;
            String name = lastLocation.getAddress().province;// 得到定位省份
            mAdapter.notifyDataSetChanged();
            if (!Tools.isNull(name) && name.endsWith("市")) {
                name = name.replaceAll("市", "");
            } else if (!Tools.isNull(name) && name.endsWith("省")) {
                name = name.replaceAll("省", "");
            }
            String byId = findDB.getProvinceById(name);
//            App.cityId = byId;
//            App.cityName = name;
            gpsEntity.setId(byId);
            gpsEntity.setName(name);

        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocClient != null) {
            mLocClient.stop();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (!Tools.isNull(p_id)) {
                    Intent intent = new Intent();
                    intent.putExtra("name", p_name);
                    intent.putExtra("id", p_id);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    T.showToast(mContext, "请先选择定位地区~");
                }
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}
